#!/bin/bash

PACKAGE_DIR=/home/soft

# 安装JDK
INSTALL_JDK(){
    mkdir -p /usr/java $PACKAGE_DIR && cd $PACKAGE_DIR
    wget -c http://soft.hc-yun.com/base/software/jdk-8u211-linux-x64.tar.gz
    tar zxf jdk-8u211-linux-x64.tar.gz -C /usr/java/

    # 配置环境变量
    echo '#!/bin/bash' > /etc/profile.d/jdk.sh
    echo 'export JAVA_HOME=/usr/java/jdk1.8.0_211' >> /etc/profile.d/jdk.sh
    echo 'export JRE_HOME=${JAVA_HOME}/jre' >> /etc/profile.d/jdk.sh
    echo 'export CLASSPATH=.:$JAVA_HOME/lib/dt.jar:$JAVA_HOME/lib/tools.jar:$JRE_HOME/lib:$CLASSPATH' >> /etc/profile.d/jdk.sh
    echo 'export PATH=$JAVA_HOME/bin:$PATH' >> /etc/profile.d/jdk.sh

    # 读取环境变量
    chmod +x /etc/profile.d/jdk.sh
    source /etc/profile.d/jdk.sh
}

INSTALL_JENKINS(){
    # 创建服务用户
    groupadd -g 995 jenkins
    useradd -d /home/jenkins -r -g jenkins -u 997 -s /bin/false jenkins

    # 配置变量
    JENKINS_LOG_DIR=/var/log/jenkins
    JENKINS_HOME=/home/jenkins/data
    JENKINS_INSTALL_DIR=/home/jenkins
    JENKINS_WEB_ROOT=/var/cache/jenkins/war

    # 下载war包
    cd $JENKINS_INSTALL_DIR
    wget -c https://mirrors.tuna.tsinghua.edu.cn/jenkins/war-stable/latest/jenkins.war

    # 创建数据目录 授权
    mkdir -p $JENKINS_INSTALL_DIR $JENKINS_WEB_ROOT $JENKINS_HOME
    chown -Rf jenkins:jenkins $JENKINS_INSTALL_DIR $JENKINS_WEB_ROOT $JENKINS_HOME

    # 创建配置文件
    source /etc/profile
    cat > /etc/sysconfig/jenkins <<EOF
JENKINS_JAVA_OPTIONS="-Djava.awt.headless=true"
JENKINS_LISTEN_ADDRESS=""
JENKINS_HTTPS_PORT=""
JENKINS_HTTPS_KEYSTORE=""
JENKINS_HTTPS_KEYSTORE_PASSWORD=""
JENKINS_HTTPS_LISTEN_ADDRESS=""
JENKINS_HTTP2_PORT=""
JENKINS_HTTP2_LISTEN_ADDRESS=""
JENKINS_DEBUG_LEVEL="5"
JENKINS_ENABLE_ACCESS_LOG="no"
JENKINS_HANDLER_MAX="100"
JENKINS_HANDLER_IDLE="20"
JENKINS_EXTRA_LIB_FOLDER=""
JENKINS_ARGS=""

JENKINS_PORT="8080"
JENKINS_USER="jenkins"
JENKINS_HOME="$JENKINS_HOME"
JENKINS_JAVA_CMD="$(command -v java)"
JENKINS_LOG_DIR="$JENKINS_LOG_DIR"
JENKINS_INSTALL_DIR="$JENKINS_INSTALL_DIR"
JENKINS_WEB_ROOT="$JENKINS_WEB_ROOT"
JENKINS_PID_FILE="/var/run/jenkins.pid"
JENKINS_LOCKFILE="/var/lock/subsys/jenkins"
JENKINS_WAR="$JENKINS_INSTALL_DIR/jenkins.war"
EOF

    # 创建服务启动脚本
    cat > /etc/init.d/jenkins <<'EOF'
#!/bin/sh

###############################################################################
#
# chkconfig: 35 99 01
# description: Jenkins Automation Server
#
###############################################################################
### BEGIN INIT INFO
# Provides:          jenkins
# Required-Start:    $local_fs $remote_fs $network $time $named
# Should-Start: $time sendmail
# Required-Stop:     $local_fs $remote_fs $network $time $named
# Should-Stop: $time sendmail
# Default-Start:     3 5
# Default-Stop:      0 1 2 6
# Short-Description: Jenkins Automation Server
# Description:       Jenkins Automation Server
### END INIT INFO

# Check for existence of needed config file and read it
JENKINS_CONFIG=/etc/sysconfig/jenkins
test -e "$JENKINS_CONFIG" || { echo "$JENKINS_CONFIG not existing";
	if [ "$1" = "stop" ]; then exit 0;
	else exit 6; fi; }
test -r "$JENKINS_CONFIG" || { echo "$JENKINS_CONFIG not readable. Perhaps you forgot 'sudo'?";
	if [ "$1" = "stop" ]; then exit 0;
	else exit 6; fi; }

# Source function library.
. /etc/init.d/functions

# Read config
[ -f "$JENKINS_CONFIG" ] && . "$JENKINS_CONFIG"

# Check for missing binaries (stale symlinks should not happen)
test -r "$JENKINS_WAR" || { echo "$JENKINS_WAR not installed";
	if [ "$1" = "stop" ]; then exit 0;
	else exit 5; fi; }

# Set up environment accordingly to the configuration settings
[ -n "$JENKINS_HOME" ] || { echo "JENKINS_HOME not configured in $JENKINS_CONFIG";
	if [ "$1" = "stop" ]; then exit 0;
	else exit 6; fi; }
[ -d "$JENKINS_HOME" ] || { echo "JENKINS_HOME directory does not exist: $JENKINS_HOME";
	if [ "$1" = "stop" ]; then exit 0;
	else exit 1; fi; }

JAVA_CMD="$JENKINS_JAVA_CMD $JENKINS_JAVA_OPTIONS -DJENKINS_HOME=$JENKINS_HOME -jar $JENKINS_WAR"
PARAMS="--logfile=$JENKINS_LOG_DIR/jenkins.log --webroot=$JENKINS_WEB_ROOT --daemon"
[ -n "$JENKINS_PORT" ] && PARAMS="$PARAMS --httpPort=$JENKINS_PORT"
[ -n "$JENKINS_LISTEN_ADDRESS" ] && PARAMS="$PARAMS --httpListenAddress=$JENKINS_LISTEN_ADDRESS"
[ -n "$JENKINS_HTTPS_PORT" ] && PARAMS="$PARAMS --httpsPort=$JENKINS_HTTPS_PORT"
[ -n "$JENKINS_HTTPS_KEYSTORE" ] && PARAMS="$PARAMS --httpsKeyStore=$JENKINS_HTTPS_KEYSTORE"
[ -n "$JENKINS_HTTPS_KEYSTORE_PASSWORD" ] && PARAMS="$PARAMS --httpsKeyStorePassword='$JENKINS_HTTPS_KEYSTORE_PASSWORD'"
[ -n "$JENKINS_HTTPS_LISTEN_ADDRESS" ] && PARAMS="$PARAMS --httpsListenAddress=$JENKINS_HTTPS_LISTEN_ADDRESS"
[ -n "$JENKINS_HTTP2_PORT" ] && PARAMS="$PARAMS --http2Port=$JENKINS_HTTP2_PORT"
[ -n "$JENKINS_HTTP2_LISTEN_ADDRESS" ] && PARAMS="$PARAMS --http2ListenAddress=$JENKINS_HTTP2_LISTEN_ADDRESS"
[ -n "$JENKINS_DEBUG_LEVEL" ] && PARAMS="$PARAMS --debug=$JENKINS_DEBUG_LEVEL"
[ -n "$JENKINS_HANDLER_STARTUP" ] && PARAMS="$PARAMS --handlerCountStartup=$JENKINS_HANDLER_STARTUP"
[ -n "$JENKINS_HANDLER_MAX" ] && PARAMS="$PARAMS --handlerCountMax=$JENKINS_HANDLER_MAX"
[ -n "$JENKINS_HANDLER_IDLE" ] && PARAMS="$PARAMS --handlerCountMaxIdle=$JENKINS_HANDLER_IDLE"
[ -n "$JENKINS_EXTRA_LIB_FOLDER" ] && PARAMS="$PARAMS --extraLibFolder=$JENKINS_EXTRA_LIB_FOLDER"
[ -n "$JENKINS_ARGS" ] && PARAMS="$PARAMS $JENKINS_ARGS"

if [ "$JENKINS_ENABLE_ACCESS_LOG" = "yes" ]; then
    PARAMS="$PARAMS --accessLoggerClassName=winstone.accesslog.SimpleAccessLogger --simpleAccessLogger.format=combined --simpleAccessLogger.file=$JENKINS_LOG_DIR/access_log"
fi

RETVAL=0

case "$1" in
    start)
	echo -n "Starting Jenkins "
	daemon --user "$JENKINS_USER" --pidfile "$JENKINS_PID_FILE" $JAVA_CMD $PARAMS > /dev/null
	RETVAL=$?
	if [ $RETVAL = 0 ]; then
	    success
	    echo > "$JENKINS_PID_FILE"  # just in case we fail to find it
            MY_SESSION_ID=`/bin/ps h -o sess -p $$`
            # get PID
            /bin/ps hww -u "$JENKINS_USER" -o sess,ppid,pid,cmd | \
            while read sess ppid pid cmd; do
		[ "$ppid" = 1 ] || continue
		# this test doesn't work because Jenkins sets a new Session ID
                # [ "$sess" = "$MY_SESSION_ID" ] || continue
	       	echo "$cmd" | grep $JENKINS_WAR > /dev/null
		[ $? = 0 ] || continue
		# found a PID
		echo $pid > "$JENKINS_PID_FILE"
	    done
	    touch $JENKINS_LOCKFILE
	else
	    failure
	fi
	echo
	;;
    stop)
	echo -n "Shutting down Jenkins "
	killproc jenkins
	rm -f $JENKINS_LOCKFILE
	RETVAL=$?
	echo
	;;
    try-restart|condrestart)
	if test "$1" = "condrestart"; then
		echo "${attn} Use try-restart ${done}(LSB)${attn} rather than condrestart ${warn}(RH)${norm}"
	fi
	$0 status
	if test $? = 0; then
		$0 restart
	else
		: # Not running is not a failure.
	fi
	;;
    restart)
	$0 stop
	$0 start
	;;
    force-reload)
	echo -n "Reload service Jenkins "
	$0 try-restart
	;;
    reload)
    	$0 restart
	;;
    status)
    	status jenkins
	RETVAL=$?
	;;
    probe)
	## Optional: Probe for the necessity of a reload, print out the
	## argument to this init script which is required for a reload.
	## Note: probe is not (yet) part of LSB (as of 1.9)

	test "$JENKINS_CONFIG" -nt "$JENKINS_PID_FILE" && echo reload
	;;
    *)
	echo "Usage: $0 {start|stop|status|try-restart|restart|force-reload|reload|probe}"
	exit 1
	;;
esac
exit $RETVAL
EOF

    chmod +x /etc/init.d/jenkins
    chkconfig jenkins on
    systemctl restart jenkins
}

INSTALL_MAVEN(){
    # install maven
    which mvn > /dev/null 2>&1
    if [ $? -ne 0  ];then
        wget -c http://$SERVER/Microservice/apache-maven-3.6.1-bin.tar.gz
        tar -xf apache-maven-3.6.1-bin.tar.gz -C /usr/local/src
        ln -sf /usr/local/src/apache-maven-3.6.1 /usr/local/maven
        echo -e "\n# maven env" > /etc/profile/maven.sh
        echo "export MAVEN_HOME=/usr/local/maven" >> /etc/profile/maven.sh
        echo 'export PATH=$PATH:$MAVEN_HOME/bin' >> /etc/profile/maven.sh

        line=$(grep -rn '<mirrors>' ${BIN_DIR}/maven/conf/settings.xml | awk -F : '{print $1}')
        sed -i "${line}a\    </mirror>" /usr/local/maven/conf/settings.xml
        sed -i "${line}a\        <url>http://maven.aliyun.com/nexus/content/groups/public/</url>" /usr/local/maven/conf/settings.xml
        sed -i "${line}a\        <mirrorOf>*,\!maven_nexus_201</mirrorOf>" /usr/local/maven/conf/settings.xml
        sed -i "${line}a\        <id>aliyun_nexus</id>" /usr/local/maven/conf/settings.xml
        sed -i "${line}a\    <mirror>" /usr/local/maven/conf/settings.xml
        line=$(grep -rn '<pluginGroups>' /usr/local/maven/conf/settings.xml | awk -F : '{print $1}')
        sed -i "${line}a\      <pluginGroup>com.spotify</pluginGroup>" /usr/local/maven/conf/settings.xml
        sed -i '48a\    <localRepository>/var/lib/maven/repo</localRepository>' /usr/local/maven/conf/settings.xml

        source /etc/profile && mvn -v
    fi
}